var colNames = null;
var colModel = null;
var groupHeaders = null;
var flag = false;
var jqGridFlag = true;
$(function() {
	$.ajax({
		type : "POST",
		url : baseURL + "comcollectionrecord/initialization",
		success : function(r) {
			if (r.code === 0) {
				$("#apportionSd").val(r.apportionSd);
				$("#apportionEd").val(r.apportionEd);
				colNames = r.colNames;
				colModel = r.colModel;
				groupHeaders = r.groupHeaders;
				firstLoad();
				setGroupHeaders();
			} else {
				alert(r.msg);
			}
		}
	});
	$('.am-selected-list').find('li').click(function() {
		flag = true;
	})
});

function firstLoad() {
	var apportionSd = $("#apportionSd").val();
	var apportionEd = $("#apportionEd").val();
	$("#jqGrid")
			.jqGrid(
					{
						url : baseURL + 'comcollectionrecord/list',
						datatype : "json",
						colNames : colNames,
						colModel : colModel,
						viewrecords : true,
						height : 385,
						rowNum : 10,
						rowList : [ 10, 30, 50 ],
						rownumbers : true,
						rownumWidth : 25,
						autowidth : true,
						shrinkToFit : false,
						footerrow : true,
						sortable : false,
						multiselect : true,
						pager : "#jqGridPager",
						jsonReader : {
							root : "page.list",
							page : "page.currPage",
							total : "page.totalPage",
							records : "page.totalCount"
						},
						prmNames : {
							page : "page",
							rows : "limit",
							order : "order"
						},
						gridComplete : function() {
							$
									.each(
											$("td[aria-describedby='jqGrid_billNo']"),
											function(i, n) {
												$(n)
														.html(
																"<a href='javascript:;' data-url='"
																		+ baseURL
																		+ "comcollectionrecord/mimeograph?billNo="
																		+ $(n)
																				.text()
																		+ "'>"
																		+ $(n)
																				.text()
																		+ "</a>");
											});
							$("a").click(
									function() {
										var url = $(this).attr("data-url");
										if (url) {
											var num = url.indexOf("?")
											if (num != -1) {
												location.href = $(this).attr(
														"data-url")
														+ "&token=" + token;
											} else {
												location.href = $(this).attr(
														"data-url")
														+ "?token=" + token;
											}
										}
									});
							// jqGrid底部合计
							var rowNum = parseInt($(this).getGridParam(
									"records"), 10);
							if (rowNum > 0) {
								var jz = {};
								$(".ui-jqgrid-sdiv").show();
								for (var i = 9; i < colModel.length - 1; i++) {
									jz[colModel[i].name] = $(this).getCol(
											colModel[i].name, false, "sum")
											.toFixed(2);
								}
								$(this).footerData("set", jz); // 将合计值显示出来
								$(".frozen-sdiv.ui-jqgrid-sdiv").find(
										"td[aria-describedby='jqGrid_billNo']")
										.empty().text("合计");
							} else {
								$(".ui-jqgrid-sdiv").hide();
							}
							if (jqGridFlag) {
								// 冻结列
								$("#jqGrid").jqGrid('setFrozenColumns');
								airbus();
								frozenDislocation();
								jqGridFlag = false;
							}
							setTimeout(function() {
								$('.frozen-bdiv.ui-jqgrid-bdiv').height(
										$('.frozen-bdiv.ui-jqgrid-bdiv')
												.height() - 1)
							}, 100);
						}
					});
};
function reLoad() {
	$("#jqGridTable").empty().html(
			'<table id="jqGrid"></table><div id="jqGridPager"></div>');
	var collectionDaysSd = $("#collectionDaysSd").val();
	var collectionDaysEd = $("#collectionDaysEd").val();
	var items = $(".am-selected-status.am-fl").text();
	$("#jqGrid")
			.jqGrid(
					{
						url : baseURL + 'comcollectionrecord/list',
						datatype : "json",
						postData : {
							'collectionDaysSd' : collectionDaysSd,
							'collectionDaysEd' : collectionDaysEd,
							'buildIds' : vm.q.buildIds,
							'assetIds' : vm.q.assetIds,
							'contractNo' : vm.q.contractNo,
							'billNo' : vm.q.billNo,
							'gatheringMethod' : vm.q.gatheringMethod,
							'renter' : vm.q.renter,
							'items' : items
						},
						colNames : colNames,
						colModel : colModel,
						viewrecords : true,
						height : 385,
						rowNum : 10,
						rowList : [ 10, 30, 50 ],
						rownumbers : true,
						rownumWidth : 25,
						autowidth : true,
						shrinkToFit : false,
						footerrow : true,
						sortable : false,
						footerrow : true,
						multiselect : true,
						pager : "#jqGridPager",
						jsonReader : {
							root : "page.list",
							page : "page.currPage",
							total : "page.totalPage",
							records : "page.totalCount"
						},
						prmNames : {
							page : "page",
							rows : "limit",
							order : "order"
						},
						gridComplete : function() {
							$
									.each(
											$("td[aria-describedby='jqGrid_billNo']"),
											function(i, n) {
												$(n)
														.html(
																"<a href='javascript:;' data-url='"
																		+ baseURL
																		+ "comcollectionrecord/mimeograph?billNo="
																		+ $(n)
																				.text()
																		+ "'>"
																		+ $(n)
																				.text()
																		+ "</a>");
											});
							$("a").click(
									function() {
										var url = $(this).attr("data-url");
										if (url) {
											var num = url.indexOf("?")
											if (num != -1) {
												location.href = $(this).attr(
														"data-url")
														+ "&token=" + token;
											} else {
												location.href = $(this).attr(
														"data-url")
														+ "?token=" + token;
											}
										}
									});
							// jqGrid底部合计
							var rowNum = parseInt($(this).getGridParam(
									"records"), 10);
							if (rowNum > 0) {
								var jz = {};
								$(".ui-jqgrid-sdiv").show();
								for (var i = 9; i < colModel.length - 1; i++) {
									jz[colModel[i].name] = $(this).getCol(
											colModel[i].name, false, "sum")
											.toFixed(2);
								}
								$(this).footerData("set", jz); // 将合计值显示出来
								$(".frozen-sdiv.ui-jqgrid-sdiv").find(
										"td[aria-describedby='jqGrid_billNo']")
										.empty().text("合计");
							} else {
								$(".ui-jqgrid-sdiv").hide();
							}
							if (jqGridFlag) {
								// 冻结列
								$("#jqGrid").jqGrid('setFrozenColumns');
								airbus();
								frozenDislocation();
								jqGridFlag = false;
							}
							setTimeout(function() {
								$('.frozen-bdiv.ui-jqgrid-bdiv').height(
										$('.frozen-bdiv.ui-jqgrid-bdiv')
												.height() - 1)
							}, 100);
						}
					});
};
function setGroupHeaders() {
	$("#jqGrid").jqGrid('setGroupHeaders', {
		useColSpanStyle : true,
		groupHeaders : groupHeaders
	});
};
function airbus() {
	$(".ui-jqgrid-sdiv").find("td[aria-describedby='jqGrid_billNo']").empty()
			.text("合计");
	$(".frozen-sdiv.ui-jqgrid-sdiv").find(
			"td[aria-describedby='jqGrid_billNo']").empty().text("合计");
};
function frozenDislocation() {
	// 冻结错位解决
	var bdivTop = -1;
	var sdivTop = -1;
	// opera 不需要hack
	if (navigator.userAgent.indexOf("Opera") >= 0) {
		divTop = 0;
		bdivTop = 0;
	}
	$('.frozen-bdiv.ui-jqgrid-bdiv').css({
		top : $('.frozen-bdiv.ui-jqgrid-bdiv').position().top + bdivTop
	});
	$('.frozen-sdiv.ui-jqgrid-sdiv').css({
		top : $('.frozen-sdiv.ui-jqgrid-sdiv').position().top + sdivTop
	});
};
var vm = new Vue(
		{
			el : '#rrapp',
			data : {
				showList : true,
				title : null,
				comCollectionRecord : {
					gatheringMethod : ""
				},
				q : {
					gatheringMethod : ""
				},
			},
			methods : {
				exportExcel : function() {
					vm.q.collectionDaysSd = $('#collectionDaysSd').val();
					vm.q.collectionDaysEd = $('#collectionDaysEd').val();
					vm.q.items = $(".am-selected-status.am-fl").text();
					var url = "comcollectionrecord/export?items=" + vm.q.items
							+ "&token=" + token;
					if (vm.q.collectionDaysSd) {
						url += "&collectionDaysSd=" + vm.q.collectionDaysSd;
					}
					if (vm.q.collectionDaysEd) {
						url += "&collectionDaysEd=" + vm.q.collectionDaysEd;
					}
					if (vm.q.buildIds) {
						url += "&buildIds=" + vm.q.buildIds;
					}
					if (vm.q.assetIds) {
						url += "&assetIds=" + vm.q.assetIds;
					}
					if (vm.q.contractNo) {
						url += "&contractNo=" + vm.q.contractNo;
					}
					if (vm.q.billNo) {
						url += "&billNo=" + vm.q.billNo;
					}
					if (vm.q.gatheringMethod) {
						url += "&gatheringMethod=" + vm.q.gatheringMethod;
					}
					if (vm.q.renter) {
						url += "&renter=" + vm.q.renter;
					}
					location.href = baseURL + url;
				},
				getUser : function() {
					$.getJSON(baseURL + "sys/user/info", function(r) {
						vm.comCollectionRecord.user = r.user;
					});
				},
				query : function() {
					vm.reload();
				},
				add : function() {
					vm.showList = false;
					vm.title = "新增";
					vm.comCollectionRecord = {
						gatheringMethod : null
					};
					$("#table").find("input").val('');
					$("#table").find("textarea").val('');
					$("#table").find("label").text('');
					$.getJSON(baseURL + "sys/user/info", function(r) {
						$("#realName").text(r.user.realName);
					});
					$.getJSON(baseURL + "comcollectionrecord/companyName",
							function(r) {
								$("#companyName").text(r.companyName);
							});
				},
				update : function(event) {
					var serialNo = getSelectedRow();
					if (serialNo == null) {
						return;
					}
					vm.showList = false;
					vm.title = "修改";
					vm.getInfo(serialNo);
					$.getJSON(baseURL + "sys/user/info", function(r) {
						$("#realName").text(r.user.realName);
					});
				},
				saveOrUpdate : function(event) {
					var comCrChargingitemList = [];
					var allTr = $("#table tr");
					for (var i = 1; i < allTr.length - 1; i++) {
						var tr = allTr.eq(i);
						var comCrChargingitem = {};
						comCrChargingitem['chargingItem'] = tr.find('td').eq(0)
								.text().trim();
						comCrChargingitem['serialNo'] = tr.find('td').eq(0)
								.find('input').val();
						comCrChargingitem['univalent'] = tr.find('td').eq(1)
								.find('input').val();
						comCrChargingitem['acreage'] = tr.find('td').eq(2)
								.find('input').val();
						comCrChargingitem['chargingSd'] = tr.find('td').eq(3)
								.find('input').eq(0).val();
						comCrChargingitem['chargingEd'] = tr.find('td').eq(3)
								.find('input').eq(1).val();
						comCrChargingitem['month'] = tr.find('td').eq(4).find(
								"label").text().trim();
						comCrChargingitem['amountPayable'] = tr.find('td')
								.eq(5).find("label").text().trim();
						comCrChargingitem['payAmount'] = tr.find('td').eq(6)
								.find('input').val();
						comCrChargingitem['remark'] = tr.find('td').eq(7).find(
								'textarea').val().trim();
						comCrChargingitem['sort'] = i;
						comCrChargingitemList.push(comCrChargingitem);
					}
					vm.comCollectionRecord.comCrChargingitemList = comCrChargingitemList;
					var url = vm.comCollectionRecord.serialNo == null ? "comcollectionrecord/save"
							: "comcollectionrecord/update";
					$
							.ajax({
								type : "POST",
								url : baseURL + url,
								data : JSON.stringify(vm.comCollectionRecord),
								success : function(r) {
									if (r.code === 0) {
										alert(
												'操作成功',
												function(index) {
													location.href = baseURL
															+ "comcollectionrecord/mimeograph?billNo="
															+ r.billNo
															+ "&token=" + token;
												});
									} else {
										alert(r.msg);
									}
								}
							});
				},
				del : function(event) {
					var serialNumbers = getSelectedRows();
					if (serialNumbers == null) {
						return;
					}
					confirm('确定要删除选中的记录？', function() {
						$.ajax({
							type : "POST",
							url : baseURL + "comcollectionrecord/delete",
							data : JSON.stringify(serialNumbers),
							success : function(r) {
								if (r.code == 0) {
									alert('操作成功', function(index) {
										$("#jqGrid").trigger("reloadGrid");
									});
								} else {
									alert(r.msg);
								}
							}
						});
					});
				},
				getInfo : function(serialNumber) {
					$
							.get(
									baseURL + "comcollectionrecord/info/"
											+ serialNumber,
									function(r) {
										$("#table").find("input").val('');
										$("#table").find("textarea").val('');
										$("#table").find("label").val('');
										vm.comCollectionRecord = r.comCollectionRecord;
										if (vm.comCollectionRecord.comCrChargingitemList == null) {
											return;
										}
										var allTr = $("#table tr");
										for (var i = 0; i < vm.comCollectionRecord.comCrChargingitemList.length; i++) {
											var comCrChargingitem = vm.comCollectionRecord.comCrChargingitemList[i];
											var tr = allTr.eq(i + 1);
											tr
													.find('td')
													.eq(0)
													.find('input')
													.val(
															comCrChargingitem.serialNo);
											tr
													.find('td')
													.eq(1)
													.find('input')
													.val(
															comCrChargingitem.univalent);
											tr
													.find('td')
													.eq(2)
													.find('input')
													.val(
															comCrChargingitem.acreage);
											tr
													.find('td')
													.eq(3)
													.find('input')
													.eq(0)
													.val(
															comCrChargingitem.chargingSd);
											tr
													.find('td')
													.eq(3)
													.find('input')
													.eq(1)
													.val(
															comCrChargingitem.chargingEd);
											tr
													.find('td')
													.eq(4)
													.find('label')
													.text(
															comCrChargingitem.month);
											tr
													.find('td')
													.eq(5)
													.find('label')
													.text(
															comCrChargingitem.amountPayable);
											tr
													.find('td')
													.eq(6)
													.find('input')
													.val(
															comCrChargingitem.payAmount);
											tr
													.find('td')
													.eq(7)
													.find('textarea')
													.val(
															comCrChargingitem.remark);
										}
										amountPayableTotal();
										payAmountTotal();
									});
				},
				reload : function(event) {
					vm.showList = true;
					var collectionDaysSd = $("#collectionDaysSd").val();
					var collectionDaysEd = $("#collectionDaysEd").val();
					var items = $(".am-selected-status.am-fl").text();
					if (flag) {
						// 改变jqgrid表头字段
						$.ajax({
							type : "POST",
							url : baseURL
									+ "comcollectionrecord/changeJqGrid?items="
									+ items,
							success : function(r) {
								if (r.code === 0) {
									colNames = r.colNames;
									colModel = r.colModel;
									caption = r.caption;
									groupHeaders = r.groupHeaders;
									jqGridFlag = true;
									reLoad();
									setGroupHeaders();
								} else {
									alert(r.msg);
								}
							}
						});
						flag = false;
					} else {
						var page = $("#jqGrid").jqGrid('getGridParam', 'page');
						$("#jqGrid").jqGrid('setGridParam', {
							postData : {
								'collectionDaysSd' : collectionDaysSd,
								'collectionDaysEd' : collectionDaysEd,
								'buildIds' : vm.q.buildIds,
								'assetIds' : vm.q.assetIds,
								'contractNo' : vm.q.contractNo,
								'billNo' : vm.q.billNo,
								'gatheringMethod' : vm.q.gatheringMethod,
								'renter' : vm.q.renter,
								'items' : items
							},
							page : page
						}).trigger("reloadGrid");
					}
				}
			}
		});
$('#collectionDays').datepicker().on(
		'changeDate.datepicker.amui',
		function(event) {
			var date = new Date(event.date);
			var year = date.getFullYear();
			var month = date.getMonth() + 1;
			if (month < 10) {
				month = '0' + month;
			}
			var day = date.getDate();
			if (day < 10) {
				day = '0' + day;
			}
			$('#collectionDays').val(year + '-' + month + '-' + day);
			vm.comCollectionRecord.collectionDays = year + '-' + month + '-'
					+ day;
		});
$(".univalent").keyup(
		function() {
			var univalent = $(this).val();
			var acreage = $(this).parent().next().find("input").val();
			var month = $(this).parent().next().next().next().text();
			var amountPayable = getAmountPayable(univalent, acreage, month);
			if (amountPayable == -1) {
				$(this).parent().next().next().next().next().find("label")
						.text("");
			} else {
				$(this).parent().next().next().next().next().find("label")
						.text(amountPayable);
			}
			amountPayableTotal();
		});
$(".acreage").keyup(
		function() {
			var acreage = $(this).val();
			var univalent = $(this).parent().prev().find("input").val();
			var month = $(this).parent().next().next().text();
			var amountPayable = getAmountPayable(univalent, acreage, month);
			if (amountPayable == -1) {
				$(this).parent().next().next().next().find("label").text("");
			} else {
				$(this).parent().next().next().next().find("label").text(
						amountPayable);
			}
			amountPayableTotal();
		});
$(".chargingSd").datepicker().on('changeDate.datepicker.amui', function(event) {
	var date = new Date(event.date);
	var year = date.getFullYear();
	var month = date.getMonth() + 1;
	if (month < 10) {
		month = '0' + month;
	}
	var day = date.getDate();
	if (day < 10) {
		day = '0' + day;
	}
	var chargingSd = year + '-' + month + '-' + day;
	$(this).val(chargingSd);
	var chargingEd = $(this).siblings("input").val();
	var month = getMonth(chargingSd, chargingEd);
	if (month == -1) {
		return;
	}
	var billingCycle = $(this).parent();
	billingCycle.next().find("label").text(month);
	var acreage = billingCycle.prev().find("input").val();
	var univalent = billingCycle.prev().prev().find("input").val();
	var amountPayable = getAmountPayable(univalent, acreage, month);
	if (amountPayable == -1) {
		return;
	}
	billingCycle.next().next().find("label").text(amountPayable);
	amountPayableTotal();
});
$(".chargingEd").datepicker().on('changeDate.datepicker.amui', function(event) {
	var date = new Date(event.date);
	var year = date.getFullYear();
	var month = date.getMonth() + 1;
	if (month < 10) {
		month = '0' + month;
	}
	var day = date.getDate();
	if (day < 10) {
		day = '0' + day;
	}
	var chargingEd = year + '-' + month + '-' + day;
	$(this).val(chargingEd);
	var chargingSd = $(this).siblings("input").val();
	var month = getMonth(chargingSd, chargingEd);
	if (month == -1) {
		return;
	}
	var billingCycle = $(this).parent();
	billingCycle.next().find("label").text(month);
	var acreage = billingCycle.prev().find("input").val();
	var univalent = billingCycle.prev().prev().find("input").val();
	var amountPayable = getAmountPayable(univalent, acreage, month);
	if (amountPayable == -1) {
		return;
	}
	billingCycle.next().next().find("label").text(amountPayable);
	amountPayableTotal();
});
$('.chargingSd').keyup(function(e) {
	if (e.keyCode == 8) {
		$(this).val("");
		$(this).text("");
		var billingCycle = $(this).parent();
		billingCycle.next().find("label").text("");
		billingCycle.next().next().find("label").text("");
		amountPayableTotal();
	}
});
$('.chargingEd').keyup(function(e) {
	if (e.keyCode == 8) {
		$(this).val("");
		$(this).text("");
		var billingCycle = $(this).parent();
		billingCycle.next().find("label").text("");
		billingCycle.next().next().find("label").text("");
		amountPayableTotal();
	}
});
$(".payAmount").keyup(function() {
	payAmountTotal();
});
function getMonth(chargingSd, chargingEd) {
	if (!chargingSd.match(new RegExp('^[0-9]+-[0-9]+-[0-9]+.*$'))) {
		return -1;
	}
	if (!chargingEd.match(new RegExp('^[0-9]+-[0-9]+-[0-9]+.*$'))) {
		return -1;
	}
	var startTmp = chargingSd.split("-");
	var endTmp = chargingEd.split("-");
	var dS = new Date(startTmp[0], startTmp[1] - 1, startTmp[2]);
	var dE = new Date(endTmp[0], endTmp[1] - 1, endTmp[2]);
	if (dE.getTime() - dS.getTime() < 0) {
		alert("计费开始时间不能大于计费结束时间！");
		return -1;
	}
	var distance = (dE.getTime() - dS.getTime()) / (1000 * 60 * 60 * 24 * 30);
	var month = Math.round(distance);
	if (month < 1) {
		month = 1;
	}
	return month + "";
}
function getAmountPayable(univalent, acreage, month) {
	if (!univalent.match(new RegExp('^[+-]?\\d+(\\.\\d+)?$'))) {
		return -1;
	}
	if (!acreage.match(new RegExp('^[+-]?\\d+(\\.\\d+)?$'))) {
		return -1;
	}
	if (!month.match(new RegExp('^[+-]?\\d+(\\.\\d+)?$'))) {
		return -1;
	}
	var amountPayable = parseFloat(univalent) * parseFloat(acreage)
			* parseFloat(month);
	;
	return amountPayable;
}
function amountPayableTotal() {
	var amountPayableTotal = 0.0;
	var rows = $("#table").find("tr").length;
	for (var i = 1; i < rows - 1; i++) {
		var amountPayable = $("#table tr:eq(" + i + ") td:eq(5)").text();
		if (amountPayable != undefined && amountPayable != ""
				&& amountPayable != null) {
			amountPayableTotal += parseFloat(amountPayable);
		}
	}
	$("#amountPayableTotal").text(amountPayableTotal);
};
function payAmountTotal() {
	var payAmountTotal = 0.0;
	var rows = $("#table").find("tr").length;
	for (var i = 1; i < rows - 1; i++) {
		var payAmount = $("#table tr:eq(" + i + ") td:eq(6) input").val();
		if (payAmount != undefined && payAmount != "" && payAmount != null
				&& payAmount != "-") {
			payAmountTotal += parseFloat(payAmount);
		}
	}
	$("#payAmountTotal").text(payAmountTotal);
};